﻿using log4net;
using MXComponent.Api;
using MXComponent.DAL;
using MXComponent.Model;
using MXComponent.Views.system;
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Media;
using System.IO;
using System.Linq;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Text.RegularExpressions;

namespace MXComponent.Views.formula
{
    /// <summary>
    /// formuladown.xaml 的交互逻辑
    /// </summary>
    public partial class formuladown : Page
    {
        public static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private AxActUtlTypeLib.AxActUtlType axActUtlType = null;
        Timer timer;
        string formulahistoryid = string.Empty;
        formulahistoryDB fhistoryDB = new formulahistoryDB();
        formuladetailhistoryDB fdhistoryDB = new formuladetailhistoryDB();
        SGWindow sgWindow = new SGWindow();
        public bool open_falg = false;
        public formuladown()
        {
            InitializeComponent();
            axActUtlType = new AxActUtlTypeLib.AxActUtlType();
            WindowsFormsHost1.Child = axActUtlType;


            beforeLoad();
        }
        formulaDB formuladb = new formulaDB();
        formuladetailDB formuladetaildb = new formuladetailDB();
        private void BindFormula()
        {
            string str = " active=1";
            DataSet ds = formuladb.GetList(str);
            this.cbbformulaname.ItemsSource = ds.Tables[0].DefaultView;
            this.cbbformulaname.DisplayMemberPath = "formulaname";
            this.cbbformulaname.SelectedValuePath = "formulaid";
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            BindFormula();
            if (!open_falg)
            {
                //不加这三句会报
                //引发类型为“System.Windows.Forms.AxHost+InvalidActiveXStateException”的异常
                ((System.ComponentModel.ISupportInitialize)(axActUtlType)).BeginInit();
                ((System.ComponentModel.ISupportInitialize)(axActUtlType)).EndInit();
                axActUtlType.ActLogicalStationNumber = PLCClass.iLogicalStationNumber;

                //设置口令
                axActUtlType.ActPassword = "";
                int iReturnCode;
                //执行打开口令，并将返回值赋给iReturnCode
                iReturnCode = axActUtlType.Open();
                if (iReturnCode == 0)
                {
                    open_falg = true;
                }
                else
                {
                    axActUtlType.Disconnect();
                    axActUtlType.Close();
                    MessageBox.Show("连接PLC失败！");
                }
            }
        }

        DataTable dt = null;
        DataTable sgdt = null;
        private void BtnDown_Click(object sender, RoutedEventArgs e)
        {
            if (cbbformulaname.SelectedValue == null)
            {
                MessageBox.Show("请先选择配方！");
                cbbformulaname.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(this.txtCount.Text))
            {
                MessageBox.Show("请先输入车次！");
                txtCount.Focus();
                return;
            }
            if (!Regex.IsMatch(this.txtCount.Text, @"^[1-9]\d*$"))
            {
                MessageBox.Show("车次输入错误！");
                this.txtCount.Text = string.Empty;
                txtCount.Focus();
                return;
            }
            this.MessageTxt.Text = "";
            DataSet ds = formuladetaildb.GetViewList(string.Format(" d.formulaid={0}", cbbformulaname.SelectedValue.ToString()));
            dt = ds.Tables[0];
            dt.TableName = "TempDateTable";

            //连接后，返回的结果
            int iReturnCode;

            try
            {
                ////不加这三句会报
                ////引发类型为“System.Windows.Forms.AxHost+InvalidActiveXStateException”的异常
                //((System.ComponentModel.ISupportInitialize)(axActUtlType)).BeginInit();
                //((System.ComponentModel.ISupportInitialize)(axActUtlType)).EndInit();
                //axActUtlType.ActLogicalStationNumber = PLCClass.iLogicalStationNumber;

                ////设置口令
                //axActUtlType.ActPassword = "";

                ////执行打开口令，并将返回值赋给iReturnCode
                //iReturnCode = axActUtlType.Open();

                //通过执行的返回值来判断后续执行
                //如果执行成功，则将站点号的textbox使能为0
                //并且后续执行此类型操作
                //if (iReturnCode == 0)
                //{
                //写入寄存器的名称
                string szDeviceName = "";
                //写入 lSize(varSize) 的容量
                int iNumberOfData = 0;
                //写入到的值存放在该数组中
                List<short> valueList = new List<short>();
                List<string> addressList = new List<string>();
                Dictionary<string, short> dir = new Dictionary<string, short>();
                int planqtysum = 0;
                int errorqtysum = 0;
                foreach (DataRow dr in dt.Rows)
                {
                    //arrDviceValue.Add(Convert.ToInt16(dr["warehouseno"].ToString()));
                    //arrDviceValue.Add(Convert.ToInt16(dr["planqty"].ToString()));
                    //arrDviceValue.Add(Convert.ToInt16(dr["errorqty"].ToString()));

                    //addressList.Add("D" + (Convert.ToInt32(dr["planqtyplc"].ToString().Replace("D", "")) - 1));
                    //addressList.Add(dr["planqtyplc"].ToString());
                    //addressList.Add(dr["errorqtyplc"].ToString());

                    if (dir.ContainsKey("D" + (Convert.ToInt32(dr["planqtyplc"].ToString().Replace("D", "")) - 1)))
                    {
                        MessageBox.Show("{0}号料仓罐号PLC地址重复", dr["warehouseno"].ToString());
                    }
                    else
                    {
                        dir.Add("D" + (Convert.ToInt32(dr["planqtyplc"].ToString().Replace("D", "")) - 1), Convert.ToInt16(dr["warehouseno"].ToString()));
                    }
                    if (dir.ContainsKey(dr["planqtyplc"].ToString()))
                    {
                        MessageBox.Show("{0}号料仓设定重量PLC地址重复");
                    }
                    else
                    {
                        dir.Add(dr["planqtyplc"].ToString(), Convert.ToInt16(dr["planqty"].ToString()));
                    }
                    if (dir.ContainsKey(dr["errorqtyplc"].ToString()))
                    {
                        MessageBox.Show("{0}号料仓设定误差PLC地址重复");
                    }
                    else
                    {
                        dir.Add(dr["errorqtyplc"].ToString(), Convert.ToInt16(dr["errorqty"].ToString()));
                    }
                    planqtysum = planqtysum + Convert.ToInt16(dr["planqty"].ToString());
                    errorqtysum = errorqtysum + Convert.ToInt16(dr["errorqty"].ToString());
                }
                //PLCClass.DownFormula(arrDviceValue, this.txtCount.Value);
                //szDeviceName = string.Join("\n", PLCClass.formulaAddressList);
                //short[] tmparrDviceValue = PLCClass.formulaValueList.ToArray();
                //iNumberOfData = PLCClass.formulaAddressList.Count;

                foreach (string addressItem in PLCClass.formulaAddressList)
                {
                    if (!dir.ContainsKey(addressItem))
                    {
                        dir.Add(addressItem, 0);
                    }

                }
                foreach (KeyValuePair<string, short> diritem in dir)
                {
                    addressList.Add(diritem.Key);
                    valueList.Add(diritem.Value);
                }
                szDeviceName = string.Join("\n", addressList);
                short[] tmparrDviceValue = valueList.ToArray();
                iNumberOfData = addressList.Count;

                iReturnCode = axActUtlType.WriteDeviceRandom2(szDeviceName,
                                                                 iNumberOfData,
                                                                 ref tmparrDviceValue[0]);
                short[] finishDviceValue = new short[1];
                finishDviceValue[0] = 1;
                iReturnCode = axActUtlType.WriteDeviceRandom2("D" + PLCClass.formulaFinish + "\n", 1, ref finishDviceValue[0]);
                finishDviceValue[0] = (short)Convert.ToInt32(this.txtCount.Text);
                iReturnCode = axActUtlType.WriteDeviceRandom2("D" + PLCClass.formulaPlanCount + "\n", 1, ref finishDviceValue[0]);
                finishDviceValue[0] = (short)planqtysum;
                iReturnCode = axActUtlType.WriteDeviceRandom2("D180" + "\n", 1, ref finishDviceValue[0]);
                finishDviceValue[0] = (short)errorqtysum;
                iReturnCode = axActUtlType.WriteDeviceRandom2("D181" + "\n", 1, ref finishDviceValue[0]);
                PLCClass.ResetList();
                if (iReturnCode == 0)
                {
                    this.btnDown.IsEnabled = false;
                    this.btnReset.IsEnabled = true;
                    this.PlanCountTxt.Text = this.txtCount.Text.ToString();
                    this.dgvList.ItemsSource = dt.DefaultView;
                    formulahistoryid = Guid.NewGuid().ToString();
                    formulahistoryData fhistory = new formulahistoryData();
                    fhistory.formulahistoryid = formulahistoryid;
                    fhistory.formulaid = Convert.ToInt32(cbbformulaname.SelectedValue);
                    fhistory.plancount = Convert.ToInt32(this.txtCount.Text);
                    fhistory.createtime = DateTime.Now.ToString();
                    fhistory.createby = GlobalClass.user.userid;
                    fhistoryDB.AddRecord(fhistory);
                }
                else
                {
                    MessageBox.Show("配方下发失败！");
                }
                //}
                //else
                //{
                //    MessageBox.Show("连接PLC失败！");
                //}

            }
            catch (Exception ex)
            {
                Log.Error(ex);
                MessageBox.Show(ex.Message);
            }

        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            BindGrid();
        //    BindStatus();
            BindAlert();
            BindCheng();
            //BindImgStatus();
            SgShowsStatus();
        }
        private delegate void bindDelegate();
        private void bindAction()
        {

            try
            {
                if (dt != null)
                {
                    string szDeviceName = string.Join("\n", PLCClass.reportAddressList);
                    short[] arrDceiceValue = new short[PLCClass.reportLength];
                  
                    List<short> valueList = new List<short>();
                    List<string> addressList = new List<string>();
                    int iReturnCode = axActUtlType.ReadDeviceRandom2(szDeviceName, PLCClass.reportLength, out arrDceiceValue[0]);
                    if (iReturnCode == 0)
                    {
                        write(PLCClass.reportAddressList, arrDceiceValue);
                        Dictionary<string, string> diclistsave = new Dictionary<string, string>();
                        Dictionary<string, string> diclistshow = new Dictionary<string, string>();
                        //int count = arrDceiceValue[8];
                        //this.CountTxt.Dispatcher.Invoke(new Action(() =>
                        //{
                        //    this.CountTxt.Text = count.ToString();
                        //}));
                        int i = 0;
                        while (i < arrDceiceValue.Length)
                        {
                            if (1 == arrDceiceValue[i + 11])
                            {
                                if (!diclistsave.ContainsKey(PLCClass.reportAddressList[i + 1]))
                                {
                                    diclistsave.Add(PLCClass.reportAddressList[i + 1], arrDceiceValue[i + 1] + "|" + arrDceiceValue[i + 10]);
                                }
                                if (!diclistsave.ContainsKey(PLCClass.reportAddressList[i + 3]))
                                {
                                    diclistsave.Add(PLCClass.reportAddressList[i + 3], arrDceiceValue[i + 3] + "|" + arrDceiceValue[i + 10]);
                                }
                                if (!diclistsave.ContainsKey(PLCClass.reportAddressList[i + 5]))
                                {
                                    diclistsave.Add(PLCClass.reportAddressList[i + 5], arrDceiceValue[i + 5] + "|" + arrDceiceValue[i + 10]);
                                }
                                if (!diclistsave.ContainsKey(PLCClass.reportAddressList[i + 7]))
                                {
                                    diclistsave.Add(PLCClass.reportAddressList[i + 7], arrDceiceValue[i + 7] + "|" + arrDceiceValue[i + 10]);
                                }
                                if (!diclistsave.ContainsKey(PLCClass.reportAddressList[i + 9]))
                                {
                                    diclistsave.Add(PLCClass.reportAddressList[i + 9], arrDceiceValue[i + 9] + "|" + arrDceiceValue[i + 10]);
                                }

                            }
                            if (!diclistshow.ContainsKey(PLCClass.reportAddressList[i + 1]))
                            {
                                diclistshow.Add(PLCClass.reportAddressList[i + 1], arrDceiceValue[i + 1] + "|" + arrDceiceValue[i + 10]);
                            }
                            if (!diclistshow.ContainsKey(PLCClass.reportAddressList[i + 3]))
                            {
                                diclistshow.Add(PLCClass.reportAddressList[i + 3], arrDceiceValue[i + 3] + "|" + arrDceiceValue[i + 10]);
                            }
                            if (!diclistshow.ContainsKey(PLCClass.reportAddressList[i + 5]))
                            {
                                diclistshow.Add(PLCClass.reportAddressList[i + 5], arrDceiceValue[i + 5] + "|" + arrDceiceValue[i + 10]);
                            }
                            if (!diclistshow.ContainsKey(PLCClass.reportAddressList[i + 7]))
                            {
                                diclistshow.Add(PLCClass.reportAddressList[i + 7], arrDceiceValue[i + 7] + "|" + arrDceiceValue[i + 10]);
                            }
                            if (!diclistshow.ContainsKey(PLCClass.reportAddressList[i + 9]))
                            {
                                diclistshow.Add(PLCClass.reportAddressList[i + 9], arrDceiceValue[i + 9] + "|" + arrDceiceValue[i + 10]);
                            }
                            i = i + 12;
                        }
                        //# region 手工称量

                        List<string> SGList = new List<string>();
                        for (int s = 248; s <= 259; s++)
                        {
                            SGList.Add("D" + s);
                        }
                        szDeviceName = string.Join("\n", SGList);
                        arrDceiceValue = new short[SGList.Count];
                        iReturnCode = axActUtlType.ReadDeviceRandom2(szDeviceName, SGList.Count, out arrDceiceValue[0]);
                        if (1 == arrDceiceValue[11])
                        {
                            if (!diclistsave.ContainsKey(SGList[1]))
                            {
                                diclistsave.Add(SGList[1], arrDceiceValue[1] + "|" + arrDceiceValue[10]);
                            }
                            if (!diclistsave.ContainsKey(SGList[3]))
                            {
                                diclistsave.Add(SGList[3], arrDceiceValue[3] + "|" + arrDceiceValue[10]);
                            }
                            if (!diclistsave.ContainsKey(SGList[5]))
                            {
                                diclistsave.Add(SGList[5], arrDceiceValue[5] + "|" + arrDceiceValue[10]);
                            }
                            if (!diclistsave.ContainsKey(SGList[7]))
                            {
                                diclistsave.Add(SGList[7], arrDceiceValue[7] + "|" + arrDceiceValue[10]);
                            }
                            if (!diclistsave.ContainsKey(SGList[9]))
                            {
                                diclistsave.Add(SGList[9], arrDceiceValue[9] + "|" + arrDceiceValue[10]);
                            }
                        }
                        if (!diclistshow.ContainsKey(SGList[1]))
                        {
                            diclistshow.Add(SGList[1], arrDceiceValue[1] + "|" + arrDceiceValue[10]);
                        }
                        if (!diclistshow.ContainsKey(SGList[3]))
                        {
                            diclistshow.Add(SGList[3], arrDceiceValue[3] + "|" + arrDceiceValue[10]);
                        }
                        if (!diclistshow.ContainsKey(SGList[5]))
                        {
                            diclistshow.Add(SGList[5], arrDceiceValue[5] + "|" + arrDceiceValue[10]);
                        }
                        if (!diclistshow.ContainsKey(SGList[7]))
                        {
                            diclistshow.Add(SGList[7], arrDceiceValue[7] + "|" + arrDceiceValue[10]);
                        }
                        if (!diclistshow.ContainsKey(SGList[9]))
                        {
                            diclistshow.Add(SGList[9], arrDceiceValue[9] + "|" + arrDceiceValue[10]);
                        }
                        //#endregion


                        if (diclistshow.Count > 0)
                        {
                            //Log.Info("测试：" + diclistshow.ToString());
                            foreach (DataRow dr in dt.Rows)
                            {
                                //Log.Info("测试："+ dr["realqtyplc"].ToString());
                                //Log.Info("ContainsKey：" + diclistshow.ContainsKey(dr["realqtyplc"].ToString()));
                                if (diclistshow.ContainsKey(dr["realqtyplc"].ToString()))
                                {
                                    dr["actualplanqty"] = diclistshow[dr["realqtyplc"].ToString()].Split('|')[0];
                                    dr["currentcount"] = diclistshow[dr["realqtyplc"].ToString()].Split('|')[1];
                                    dr["actualerrorqty"] = Convert.ToInt16(dr["actualplanqty"]) - Convert.ToInt16(dr["planqty"]);
                                }
                            }
                            dt.AcceptChanges();
                            this.dgvList.ItemsSource = dt.DefaultView;
                        }

                        if (diclistsave.Count > 0)
                        {
                            foreach (DataRow dr in dt.Rows)
                            {
                                if (diclistsave.ContainsKey(dr["realqtyplc"].ToString()))
                                {
                                    dr["actualplanqty"] = diclistsave[dr["realqtyplc"].ToString()].Split('|')[0];
                                    dr["currentcount"] = diclistsave[dr["realqtyplc"].ToString()].Split('|')[1];
                                    dr["actualerrorqty"] = Convert.ToInt16(dr["actualplanqty"]) - Convert.ToInt16(dr["planqty"]);
                                    if (!addressList.Contains(dr["saveflagplc"].ToString()))
                                    {
                                        addressList.Add(dr["saveflagplc"].ToString());
                                        valueList.Add(0);
                                    }
                                }
                            }
                            dt.AcceptChanges();
                            this.dgvList.ItemsSource = dt.DefaultView;
                            //int min = int.Parse((dt.Compute("Min(currentcount)", "true").ToString()));
                            int min = 0;
                            int.TryParse((dt.Compute("Min(currentcount)", "true").ToString()), out min);
                            this.CountTxt.Dispatcher.Invoke(new Action(() =>
                            {
                                this.CountTxt.Text = min.ToString();
                                fhistoryDB.UpdateRecord(this.formulahistoryid, min);
                            }));
                            //}
                            if (addressList.Count > 0)
                            {
                                //保存数据库
                                List<formuladetailhistoryData> fdhistoryList = new List<formuladetailhistoryData>();
                                foreach (DataRow dr in dt.Rows)
                                {
                                    if (diclistsave.ContainsKey(dr["realqtyplc"].ToString()))
                                    {
                                        formuladetailhistoryData fdhistoryDate = new formuladetailhistoryData();
                                        fdhistoryDate.formulahistoryid = formulahistoryid;
                                        fdhistoryDate.formulaid = Convert.ToInt32(dr["formulaid"]);
                                        fdhistoryDate.ordernum = Convert.ToInt32(dr["currentcount"]);
                                        fdhistoryDate.planqty = Convert.ToInt32(dr["planqty"]);
                                        fdhistoryDate.realqty = Convert.ToInt32(dr["actualplanqty"]);
                                        fdhistoryDate.warehouseid = Convert.ToInt32(dr["warehouseid"]);
                                        fdhistoryDate.createtime = DateTime.Now.ToString();
                                        fdhistoryDate.materialid = Convert.ToInt32(dr["materialid"]);

                                        fdhistoryList.Add(fdhistoryDate);
                                    }
                                }
                                fdhistoryDB.AddRecordList(fdhistoryList);
                                szDeviceName = string.Join("\n", addressList);
                                short[] tmparrDviceValue = valueList.ToArray();
                                int iNumberOfData = addressList.Count;

                                iReturnCode = axActUtlType.WriteDeviceRandom2(szDeviceName,
                                                                                 iNumberOfData,
                                                                                 ref tmparrDviceValue[0]);
                            }
                            if (PlanCountTxt.Text == CountTxt.Text)
                            {
                                this.btnDown.IsEnabled = true;
                                this.btnReset.IsEnabled = false;
                                this.MessageTxt.Text = "执行完成！";
                                fhistoryDB.UpdateRecord(this.formulahistoryid);
                                dt.Rows.Clear();
                                dt.AcceptChanges();
                                this.dgvList.ItemsSource = dt.DefaultView;
                                //  MessageBox.Show("执行完成！");
                            }
                        }
                    }
                    else
                    {
                        //Log.Debug("bindActionPLC连接失败");
                    }
                    sgdt = GetNewDataTable(dt, "warehouseno in (21,22,23,24)", "warehouseno asc");
                }

            }
            catch (Exception ex)
            {
                Log.Error(ex);
                MessageBox.Show("bindAction" + ex.Message);

            }
        }
        public void write(List<string> alist, short[] arrDceiceValue)
        {
            try
            {
                string result = "";
                for (int i = 0; i < alist.Count; i++)
                {
                    result += alist[i] + ":" + arrDceiceValue[i] + ";";
                }
                Log.Info(result);
            }
            catch (Exception ex)
            {
                Log.Error(ex);

            }
        }
        public static void AddLgoToTXT(string logstring)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "operalog.txt";
            if (!System.IO.File.Exists(path))
            {
                FileStream stream = System.IO.File.Create(path);
                stream.Close();
                stream.Dispose();
            }
            using (StreamWriter writer = new StreamWriter(path, true))
            {
                writer.WriteLine(logstring);
            }
        }
        private void BindGrid()
        {
            this.Dispatcher.Invoke(new bindDelegate(bindAction));
        }

        private delegate void bindStatusDelegate();
        private void BindStatus()
        {
            this.Dispatcher.Invoke(new bindStatusDelegate(bindWHStatus));
        }


        Brush getColor(WHStatus item)
        {
            Brush reuslt = Brushes.White;
            switch (item)
            {
                case WHStatus.称量适中:
                    reuslt = Brushes.Green;

                    break;
                case WHStatus.称量超差:
                    reuslt = Brushes.Red;

                    break;
                default:
                    reuslt = Brushes.White;

                    break;
            }

            return reuslt;
        }
        private void bindWHStatus()
        {
            try
            {
                string szDeviceName = string.Join("\n", PLCClass.statusAddressList);
                short[] arrDceiceValue = new short[PLCClass.statusLength];
                int iReturnCode = axActUtlType.ReadDeviceRandom2(szDeviceName, PLCClass.statusLength, out arrDceiceValue[0]);
                if (iReturnCode == 0)
                {
                    whstatus1.Text = ((WHStatus)arrDceiceValue[0]).ToString();
                    whcount1.Text = arrDceiceValue[1].ToString();
                    whstatus1.Foreground = getColor((WHStatus)arrDceiceValue[0]);

                    whstatus2.Text = ((WHStatus)arrDceiceValue[2]).ToString();
                    whcount2.Text = arrDceiceValue[3].ToString();
                    whstatus2.Foreground = getColor((WHStatus)arrDceiceValue[2]);

                    whstatus3.Text = ((WHStatus)arrDceiceValue[4]).ToString();
                    whcount3.Text = arrDceiceValue[5].ToString();
                    whstatus3.Foreground = getColor((WHStatus)arrDceiceValue[4]);

                    whstatus4.Text = ((WHStatus)arrDceiceValue[6]).ToString();
                    whcount4.Text = arrDceiceValue[7].ToString();
                    whstatus4.Foreground = getColor((WHStatus)arrDceiceValue[6]);

                    whstatus5.Text = ((WHStatus)arrDceiceValue[8]).ToString();
                    whcount5.Text = arrDceiceValue[9].ToString();
                    whstatus5.Foreground = getColor((WHStatus)arrDceiceValue[8]);

                    whstatus6.Text = ((WHStatus)arrDceiceValue[10]).ToString();
                    whcount6.Text = arrDceiceValue[11].ToString();
                    whstatus6.Foreground = getColor((WHStatus)arrDceiceValue[10]);

                    whstatus7.Text = ((WHStatus)arrDceiceValue[12]).ToString();
                    whcount7.Text = arrDceiceValue[13].ToString();
                    whstatus7.Foreground = getColor((WHStatus)arrDceiceValue[12]);

                    whstatus8.Text = ((WHStatus)arrDceiceValue[14]).ToString();
                    whcount8.Text = arrDceiceValue[15].ToString();
                    whstatus8.Foreground = getColor((WHStatus)arrDceiceValue[14]);

                    whstatus9.Text = ((WHStatus)arrDceiceValue[16]).ToString();
                    whcount9.Text = arrDceiceValue[17].ToString();
                    whstatus9.Foreground = getColor((WHStatus)arrDceiceValue[16]);

                    whstatus10.Text = ((WHStatus)arrDceiceValue[18]).ToString();
                    whcount10.Text = arrDceiceValue[19].ToString();
                    whstatus10.Foreground = getColor((WHStatus)arrDceiceValue[18]);

                    whstatus11.Text = ((WHStatus)arrDceiceValue[20]).ToString();
                    whcount11.Text = arrDceiceValue[21].ToString();
                    whstatus11.Foreground = getColor((WHStatus)arrDceiceValue[20]);

                    whstatus12.Text = ((WHStatus)arrDceiceValue[22]).ToString();
                    whcount12.Text = arrDceiceValue[23].ToString();
                    whstatus12.Foreground = getColor((WHStatus)arrDceiceValue[22]);

                    whstatus13.Text = ((WHStatus)arrDceiceValue[24]).ToString();
                    whcount13.Text = arrDceiceValue[25].ToString();
                    whstatus13.Foreground = getColor((WHStatus)arrDceiceValue[24]);

                    whstatus14.Text = ((WHStatus)arrDceiceValue[26]).ToString();
                    whcount14.Text = arrDceiceValue[27].ToString();
                    whstatus14.Foreground = getColor((WHStatus)arrDceiceValue[26]);

                    whstatus15.Text = ((WHStatus)arrDceiceValue[28]).ToString();
                    whcount15.Text = arrDceiceValue[29].ToString();
                    whstatus15.Foreground = getColor((WHStatus)arrDceiceValue[28]);

                    whstatus16.Text = ((WHStatus)arrDceiceValue[30]).ToString();
                    whcount16.Text = arrDceiceValue[31].ToString();
                    whstatus16.Foreground = getColor((WHStatus)arrDceiceValue[30]);

                    whstatus17.Text = ((WHStatus)arrDceiceValue[32]).ToString();
                    whcount17.Text = arrDceiceValue[33].ToString();
                    whstatus17.Foreground = getColor((WHStatus)arrDceiceValue[32]);

                    whstatus18.Text = ((WHStatus)arrDceiceValue[34]).ToString();
                    whcount18.Text = arrDceiceValue[35].ToString();
                    whstatus18.Foreground = getColor((WHStatus)arrDceiceValue[34]);

                    whstatus19.Text = ((WHStatus)arrDceiceValue[36]).ToString();
                    whcount19.Text = arrDceiceValue[37].ToString();
                    whstatus19.Foreground = getColor((WHStatus)arrDceiceValue[36]);

                    whstatus20.Text = ((WHStatus)arrDceiceValue[38]).ToString();
                    whcount20.Text = arrDceiceValue[39].ToString();
                    whstatus20.Foreground = getColor((WHStatus)arrDceiceValue[38]);

                    whstatus21.Text = ((WHStatus)arrDceiceValue[40]).ToString();
                    whcount21.Text = arrDceiceValue[41].ToString();
                    whstatus21.Foreground = getColor((WHStatus)arrDceiceValue[40]);

                    whstatus22.Text = ((WHStatus)arrDceiceValue[42]).ToString();
                    whcount22.Text = arrDceiceValue[43].ToString();
                    whstatus22.Foreground = getColor((WHStatus)arrDceiceValue[42]);

                    whstatus23.Text = ((WHStatus)arrDceiceValue[44]).ToString();
                    whcount23.Text = arrDceiceValue[45].ToString();
                    whstatus23.Foreground = getColor((WHStatus)arrDceiceValue[44]);

                    whstatus24.Text = ((WHStatus)arrDceiceValue[46]).ToString();
                    whcount24.Text = arrDceiceValue[47].ToString();
                    whstatus24.Foreground = getColor((WHStatus)arrDceiceValue[46]);
                }
                else
                {
                    /// Log.Debug("bindWHStatusPLC连接失败");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                MessageBox.Show("bindWHStatus" + ex.Message);
            }
        }

        private delegate void bindAlertDelegate();

        private void BindAlert()
        {
            this.Dispatcher.Invoke(new bindAlertDelegate(bindAlertAction));
        }
        private void bindAlertAction()
        {
            try
            {
                List<string> alertList = new List<string>();
                alertList.Add("D650");
                alertList.Add("D651");
                alertList.Add("D652");
                string szDeviceName = string.Join("\n", alertList);
                short[] arrDceiceValue = new short[alertList.Count];
                int iReturnCode = axActUtlType.ReadDeviceRandom2(szDeviceName, alertList.Count, out arrDceiceValue[0]);
                if (iReturnCode == 0)
                {
                    string str = Convert.ToString(arrDceiceValue[0], 2).PadLeft(16, '0');
                    str = Reverse1(str);
                    AlertTxt.Text = "";
                    for (int i = 0; i < 16; i++)
                    {
                        if (str[i] == '1' && Enum.IsDefined(typeof(P1Alert), i))
                        {
                            AlertTxt.Text = ((P1Alert)i).ToString();
                            ShowNotificationWindow(((P1Alert)i).ToString());
                        }
                    }
                    str = Convert.ToString(arrDceiceValue[1], 2).PadLeft(16, '0');
                    str = Reverse1(str);
                    for (int i = 0; i < 16; i++)
                    {
                        if (str[i] == '1' && Enum.IsDefined(typeof(P2Alert), i))
                        {
                            AlertTxt.Text = ((P2Alert)i).ToString();
                            ShowNotificationWindow(((P2Alert)i).ToString());
                        }
                    }
                    str = Convert.ToString(arrDceiceValue[2], 2).PadLeft(16, '0');
                    str = Reverse1(str);
                    for (int i = 0; i < 1; i++)
                    {
                        if (str[i] == '1' && Enum.IsDefined(typeof(P3Alert), i))
                        {
                            AlertTxt.Text = ((P3Alert)i).ToString();
                            ShowNotificationWindow(((P3Alert)i).ToString());
                        }
                    }

                }
                else
                {
                    /// Log.Debug("bindWHStatusPLC连接失败");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                MessageBox.Show("bindAlert" + ex.Message);
            }
        }

        private delegate void bindChengDelegate();
        private void BindCheng()
        {
            this.Dispatcher.Invoke(new bindChengDelegate(bindChengAction));
        }
        private void bindChengAction()
        {
            try
            {
                List<string> alertList = new List<string>();
                alertList.Add("D2000");
                alertList.Add("D2001");
                alertList.Add("D2002");
                alertList.Add("D2003");
                alertList.Add("D2004");
                alertList.Add("D8808");
                string szDeviceName = string.Join("\n", alertList);
                short[] arrDceiceValue = new short[alertList.Count];
                int iReturnCode = axActUtlType.ReadDeviceRandom2(szDeviceName, alertList.Count, out arrDceiceValue[0]);
                if (iReturnCode == 0)
                {
                    this.P1.Text = (Convert.ToInt32(arrDceiceValue[0].ToString()) * 1.0 / 1000).ToString("0.000");

                    this.P2.Text = (Convert.ToInt32(arrDceiceValue[1].ToString()) * 1.0 / 1000).ToString("0.000");

                    this.P3.Text = (Convert.ToInt32(arrDceiceValue[2].ToString()) * 1.0 / 1000).ToString("0.000");

                    this.P4.Text = (Convert.ToInt32(arrDceiceValue[3].ToString()) * 1.0 / 1000).ToString("0.000");

                    this.P5.Text = (Convert.ToInt32(arrDceiceValue[4].ToString()) * 1.0 / 1000).ToString("0.000");

                    this.P6.Text = (Convert.ToInt32(arrDceiceValue[4].ToString()) * 1.0 / 1000).ToString("0.000");
                }
                else
                {
                    /// Log.Debug("bindWHStatusPLC连接失败");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                MessageBox.Show("bindAlert" + ex.Message);
            }
        }

        public static List<NotificationWindow> _dialogs = new List<NotificationWindow>();
        private void ShowNotificationWindow(string content)
        {
            //App.Current.Dispatcher.Invoke((Action)(() =>
            //{
            //    NotificationWindow dialog = new NotificationWindow(content);//new 一个通知
            //    dialog.Closed += Dialog_Closed;
            //    dialog.TopFrom = GetTopFrom();
            //    _dialogs.Add(dialog);
            //    dialog.ShowActivated = false;
            //    dialog.Show();
               
            //}));
        }
        private void Dialog_Closed(object sender, EventArgs e)
        {
            var closedDialog = sender as NotificationWindow;
            _dialogs.Remove(closedDialog);
        }

        double GetTopFrom()
        {
            //屏幕的高度-底部TaskBar的高度。
            double topFrom = System.Windows.SystemParameters.WorkArea.Bottom - 10;
            bool isContinueFind = _dialogs.Any(o => o.TopFrom == topFrom);

            while (isContinueFind)
            {
                topFrom = topFrom - 110;//此处100是NotifyWindow的高
                isContinueFind = _dialogs.Any(o => o.TopFrom == topFrom);
            }

            if (topFrom <= 0)
                topFrom = System.Windows.SystemParameters.WorkArea.Bottom - 10;

            return topFrom;
        }

        string Reverse1(string original)
        {
            char[] arr = original.ToCharArray();
            Array.Reverse(arr);
            return new string(arr);
        }

        void beforeLoad()
        {
            DataSet ds = fhistoryDB.GetTopView();
            if (ds.Tables != null && ds.Tables.Count > 0)
            {
                DataTable tmpdt = ds.Tables[0];
                if (tmpdt != null && tmpdt.Rows.Count > 0)
                {
                    if (tmpdt.Rows[0]["isfinish"] != DBNull.Value && Convert.ToInt32(tmpdt.Rows[0]["isfinish"]) != 1)
                    {
                        this.formulahistoryid = tmpdt.Rows[0]["formulahistoryid"].ToString();
                        ds = formuladetaildb.GetViewList(string.Format(" d.formulaid={0}", tmpdt.Rows[0]["formulaid"].ToString()));
                        this.dt = ds.Tables[0];
                        this.dt.TableName = "TempDateTable";
                        this.dgvList.ItemsSource = dt.DefaultView;
                        this.btnDown.IsEnabled = false;
                        this.btnReset.IsEnabled = true;
                        this.PlanCountTxt.Text = tmpdt.Rows[0]["plancount"].ToString();
                        this.CountTxt.Text = tmpdt.Rows[0]["realcount"].ToString();
                        cbbformulaname.SelectedValue = tmpdt.Rows[0]["formulaid"].ToString();
                        txtCount.Text = tmpdt.Rows[0]["plancount"].ToString();
                    }
                }
            }
        }


        private delegate void bindImgStatusDelegate();

        private void BindImgStatus()
        {
            this.Dispatcher.Invoke(new bindImgStatusDelegate(bindImgStatusAction));
        }
        private void bindImgStatusAction()
        {
            try
            {
                List<string> alertList = new List<string>();
                alertList.Add("D700");
                string szDeviceName = string.Join("\n", alertList);
                short[] arrDceiceValue = new short[alertList.Count];
                int iReturnCode = axActUtlType.ReadDeviceRandom2(szDeviceName, alertList.Count, out arrDceiceValue[0]);
                if (iReturnCode == 0)
                {
                    //string str = Convert.ToString(arrDceiceValue[0], 2).PadLeft(16, '0');
                    //str = Reverse1(str);
                    //AlertTxt.Text = "";
                    //for (int i = 0; i < 16; i++)
                    //{
                    //    if (str[i] == '1')
                    //    {
                    //        AlertTxt.Text = ((P1Alert)i).ToString();
                    //        ShowNotificationWindow(((P1Alert)i).ToString());
                    //    }
                    //}
                    string str = Convert.ToString(arrDceiceValue[0], 2).PadLeft(16, '0');
                    str = Reverse1(str);
                    ImgStatus1.ImageSource = str[0] == '1' ? new BitmapImage(new Uri(@"Image/Green.png", UriKind.Relative)) : new BitmapImage(new Uri(@"Image/White.png", UriKind.Relative));
                    ImgStatus2.ImageSource = str[1] == '1' ? new BitmapImage(new Uri(@"Image/Green.png", UriKind.Relative)) : new BitmapImage(new Uri(@"Image/White.png", UriKind.Relative));
                    ImgStatus3.ImageSource = str[2] == '1' ? new BitmapImage(new Uri(@"Image/Green.png", UriKind.Relative)) : new BitmapImage(new Uri(@"Image/White.png", UriKind.Relative));
                    ImgStatus4.ImageSource = str[3] == '1' ? new BitmapImage(new Uri(@"Image/Green.png", UriKind.Relative)) : new BitmapImage(new Uri(@"Image/White.png", UriKind.Relative));
                    ImgStatus5.ImageSource = str[4] == '1' ? new BitmapImage(new Uri(@"Image/Green.png", UriKind.Relative)) : new BitmapImage(new Uri(@"Image/White.png", UriKind.Relative));
                    ImgStatus6.ImageSource = str[5] == '1' ? new BitmapImage(new Uri(@"Image/Green.png", UriKind.Relative)) : new BitmapImage(new Uri(@"Image/White.png", UriKind.Relative));
                }
                else
                {
                    /// Log.Debug("bindWHStatusPLC连接失败");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                MessageBox.Show("bindAlert" + ex.Message);
            }
        }
        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            // axActUtlType.Close();
        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.formulahistoryid))
            {
                return;
            }
            int iReturnCode;
            short[] finishDviceValue = new short[1];
            finishDviceValue[0] = 1;
            iReturnCode = axActUtlType.WriteDeviceRandom2("D703" + "\n", 1, ref finishDviceValue[0]);
            if (iReturnCode == 0)
            {
                this.btnDown.IsEnabled = true;
                this.btnReset.IsEnabled = false;
                fhistoryDB.UpdateRecord(this.formulahistoryid);
                dt.Rows.Clear();
                dt.AcceptChanges();
                this.dgvList.ItemsSource = dt.DefaultView;
                this.PlanCountTxt.Text = "0";
                this.CountTxt.Text = "0";
            }
            else
            {
                MessageBox.Show("重置失败！");
            }
        }

        private delegate void SgShowsDelegate();

        private void SgShowsStatus()
        {
            this.Dispatcher.Invoke(new SgShowsDelegate(SgShow));
        }
        private void  SgShow()
        {                  
            try
            {
                List<string> alertList = new List<string>();
                alertList.Add("D460");
                string szDeviceName = string.Join("\n", alertList);
                short[] arrDceiceValue = new short[alertList.Count];
                int iReturnCode = axActUtlType.ReadDeviceRandom2(szDeviceName, alertList.Count, out arrDceiceValue[0]);
                if (iReturnCode == 0)
                {
                    if (arrDceiceValue[0] == 1)
                    {
                        sgWindow.Show();
                        sgWindow.Activate();
                        sgWindow.BindDate(sgdt);
                    }
                    else
                    {
                        sgWindow.Hide();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }

        private void Page_Initialized(object sender, EventArgs e)
        {
            timer = new Timer();
            timer.Interval = PLCClass.timerInterval;
            timer.Elapsed += new ElapsedEventHandler(timer1_Tick);
            timer.Start();

        }

        private void btnReset_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.formulahistoryid))
            {
                return;
            }
            int iReturnCode;
            short[] finishDviceValue = new short[1];



            SetWindow sw = new SetWindow(cbbformulaname.Text, this.PlanCountTxt.Text);
            if (sw.ShowDialog() == true)
            {
                int count = sw.count;
                finishDviceValue[0] = (short)count;
                iReturnCode = axActUtlType.WriteDeviceRandom2("D" + PLCClass.formulaPlanCount + "\n", 1, ref finishDviceValue[0]);
                if (iReturnCode == 0)
                {
                    App.Current.Dispatcher.Invoke((Action)(() =>
                    {
                        this.txtCount.Text = count.ToString();
                        this.PlanCountTxt.Text = count.ToString();
                        fhistoryDB.UpdateRecordForPlancount(this.formulahistoryid, count);
                    }));


                }
                else
                {
                    MessageBox.Show("重置失败！");
                }
            }
        }

        private void btnSet_Click(object sender, RoutedEventArgs e)
        {
            int iReturnCode;
            short[] finishDviceValue = new short[2];



            SetWindow2 sw = new SetWindow2();
            if (sw.ShowDialog() == true)
            {
                float count = sw.count;
                if (count.ToString().Contains("."))
                {
                    finishDviceValue[0] = short.Parse(count.ToString().Split('.')[1]);
                    finishDviceValue[1] = short.Parse(count.ToString().Split('.')[0]);
                }
                else
                {
                    finishDviceValue[0] = short.Parse("0");
                    finishDviceValue[1] = short.Parse(count.ToString());
                }
                List<string> addressList = new List<string>();
                addressList.Add("D9280");
                addressList.Add("D9281");
               string szDeviceName = string.Join("\n", addressList);
                iReturnCode = axActUtlType.WriteDeviceRandom2(szDeviceName, 2, ref finishDviceValue[0]);
                if (iReturnCode == 0)
                {
                    MessageBox.Show("写入失败！");
                }
                else
                {
                    MessageBox.Show("写入失败！");
                }
            }
        }

        private DataTable GetNewDataTable(DataTable dt, string condition, string sortstr)
        {
            DataTable newdt = new DataTable();
            newdt = dt.Clone();
            DataRow[] dr = dt.Select(condition, sortstr);

            if (dr == null || dr.Length == 0) return null;
            for (int i = 0; i < dr.Length; i++)
            {
                newdt.ImportRow((DataRow)dr[i]);
            }
            return newdt;//返回的查询结果
        }

        private void dgvList_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            var drv = e.Row.Item as DataRowView;
            if (Convert.ToDouble(drv["errorqty"]) < Convert.ToDouble(drv["actualerrorqty"]))
            {
                e.Row.Background = new SolidColorBrush(Colors.Red);
                AlertTxt.Text = string.Format("{0}误差较大，请调整！", drv["warehousename"].ToString());
            }
        }

        private void dgvList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }


    public enum WHStatus
    {
        等待 = 0,
        欠量 = 1,
        称量适中 = 2,
        称量超差 = 3
    }

    public enum P1Alert
    {
        A仪表通讯失败 = 0,
        B仪表通讯失败 = 1,
        C仪表通讯失败 = 2,
        D仪表通讯失败 = 3,
        检量秤仪表通讯失败 = 4,
        除尘风机报警 = 5,
        螺旋1A电机报警 = 6,
        螺旋1B电机报警 = 7,
        螺旋1C电机报警 = 8,
        螺旋4A电机报警 = 9,
        螺旋4B电机报警 = 10,
        螺旋4C电机报警 = 11,
        螺旋2A电机报警 = 12,
        螺旋2B电机报警 = 13,
        螺旋2C电机报警 = 14,
        螺旋3A电机报警 = 15,

    }
    public enum P2Alert
    {
        螺旋电机3B报警 = 0,
        螺旋电机3c报警 = 1,
        变频器P1报警 = 2,
        变频器P2报警 = 3,
        变频器P3报警 = 4,
        变频器P5报警 = 5,
        A秤称量超差 = 6,
        A秤称量超时 = 7,
        B秤称量超差 = 8,
        B秤称量超时 = 9,
        C秤称量超差 = 10,
        C秤称量超时 = 11,
        D秤称量超差 = 12,
        D秤称量超时 = 13
    }
    public enum P3Alert
    {
        检量超差 = 1,
        检量欠量 = 2,
        回转称量电机报警 = 3
    }
}
